package com.navinfo.parkingnavi.widget.content;

import android.content.Context;
import android.os.Looper;
import android.util.AttributeSet;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.view.ViewTreeObserver;
import android.widget.AbsListView;
import android.widget.FrameLayout;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.navinfo.parkingnavi.widget.ScrollLayout;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/*
 *com.navinfo.parkingnavi.widget.content
 *zhjch
 *2020/5/18
 *11:14
 *说明（）
 */
public class ContentRecyclerView extends RecyclerView {

    private OnLoadMoreListener moreListener ;


    private final ContentRecyclerView.CompositeScrollListener compositeScrollListener =

            new ContentRecyclerView.CompositeScrollListener();


    public void setMoreListener(OnLoadMoreListener listener){
        moreListener = listener;
    }

    public ContentRecyclerView(Context context) {

        super(context);

    }



    public ContentRecyclerView(Context context, @Nullable AttributeSet attrs) {

        super(context, attrs);

    }



    public ContentRecyclerView(Context context, @Nullable AttributeSet attrs, int defStyle) {

        super(context, attrs, defStyle);

    }



    {

        super.addOnScrollListener(compositeScrollListener);



        getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {

            @Override

            public void onGlobalLayout() {

                ViewGroup.LayoutParams layoutParams = getLayoutParams();

                ViewParent parent = getParent();

                while (parent != null) {

                    if (parent instanceof ScrollLayout) {

                        int height = ((ScrollLayout) parent).getMeasuredHeight() - ((ScrollLayout) parent).minOffset;

                        if (layoutParams.height == height) {

                            return;

                        } else {

                            layoutParams.height = height;

                            break;

                        }

                    }

                    parent = parent.getParent();

                }

                setLayoutParams(layoutParams);

            }

        });

    }





    @Override

    protected void onAttachedToWindow() {

        super.onAttachedToWindow();

        ViewParent parent = getParent();

        while (parent != null) {

            if (parent instanceof ScrollLayout) {

                ((ScrollLayout) parent).setAssociatedRecyclerView(this);

                break;

            }

            parent = parent.getParent();

        }

    }



    @Override

    protected void onDetachedFromWindow() {

        super.onDetachedFromWindow();

    }



    private void throwIfNotOnMainThread() {

        if (Looper.myLooper() != Looper.getMainLooper()) {

            throw new IllegalStateException("Must be invoked from the main thread.");

        }

    }



    private class CompositeScrollListener extends OnScrollListener {

        private final List<OnScrollListener> scrollListenerList = new

                ArrayList<RecyclerView.OnScrollListener>();



        public void addOnScrollListener(RecyclerView.OnScrollListener listener) {

            if (listener == null) {

                return;

            }

            for (RecyclerView.OnScrollListener scrollListener : scrollListenerList) {

                if (listener == scrollListener) {

                    return;

                }

            }

            scrollListenerList.add(listener);

        }



        public void removeOnScrollListener(AbsListView.OnScrollListener listener) {

            if (listener == null) {

                return;

            }

            Iterator<OnScrollListener> iterator = scrollListenerList.iterator();

            while (iterator.hasNext()) {

                RecyclerView.OnScrollListener scrollListener = iterator.next();

                if (listener == scrollListener) {

                    iterator.remove();

                    return;

                }

            }

        }

        //是否横向滑动
        private boolean isSlidingToLast = false;

        @Override

        public void onScrollStateChanged(RecyclerView view, int scrollState) {

            List<RecyclerView.OnScrollListener> listeners = new ArrayList<RecyclerView.OnScrollListener>(scrollListenerList);

            for (RecyclerView.OnScrollListener listener : listeners) {

                listener.onScrollStateChanged(view, scrollState);

            }

            //设置什么布局管理器,就获取什么的布局管理器
            LinearLayoutManager manager = (LinearLayoutManager) view.getLayoutManager();
            // 当停止滑动时
            if (scrollState == RecyclerView.SCROLL_STATE_IDLE) {
                //获取最后一个完全显示的ItemPosition ,角标值
                int lastVisibleItem = manager.findLastCompletelyVisibleItemPosition();
                //所有条目,数量值
                int totalItemCount = manager.getItemCount();

                // 判断是否滚动到底部，并且是向右滚动
                if (lastVisibleItem == (totalItemCount - 1) && isSlidingToLast) {
                    //加载更多功能的代码
                    if(moreListener != null){
                        moreListener.onLoadMore();
                    }
                }
            }

        }



        @Override

        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);

            List<RecyclerView.OnScrollListener> listeners = new ArrayList<OnScrollListener>(scrollListenerList);

            for (RecyclerView.OnScrollListener listener : listeners) {

                listener.onScrolled(recyclerView, dx, dy);

            }
            //dx用来判断横向滑动方向，dy用来判断纵向滑动方向
            //dx>0:向右滑动,dx<0:向左滑动
            //dy>0:向下滑动,dy<0:向上滑动
            if (dy > 0) {
                isSlidingToLast = true;
            } else {
                isSlidingToLast = false;
            }
        }
    }

    public interface OnLoadMoreListener{
        void onLoadMore();
    }
}